
from coffeetalk.client import iotpclient
from coffeetalk.protocol import ioelement, requests
from coffeetalk.utilities import iologger

class IOAuthenticator(object):
    
    def __init__(self):
        pass
    
    def handle_login(self,env,path,logincredentials):
        raise NotImplementedError('handle_login must be implemented in a derived class')
    
class IOSystemAuthenticator(IOAuthenticator):
    
    def __init__(self,ioclient,password):
        IOAuthenticator.__init__(self)
        
        self.ioclient = ioclient
        self.password = password
        
    def handle_login(self,env,path,logincredentials):
        
        authorizedpath = ''.join(('/System/Network/Clients/Connecting/',str(logincredentials.name),'/'))
        if logincredentials.password == self.password:
            authorizedobject = ioelement.IOElement('Response',{'type':'[Authorized]','username':logincredentials.username,'group':'System'})
        else:
            authorizedobject = ioelement.IOElement('Response',{'type':'[Unauthorized]'})
        
        self.ioclient.add(requests.Add(path=authorizedpath,iobject=authorizedobject))  
        
class IOUserAuthenticator(iotpclient.IOTPClient):
    
    def __init__(self,connectionconfig,log=iologger.IONullLogger()):
        self.log = log        
        iotpclient.IOTPClient.__init__(self,config=connectionconfig,log=self.log)
        
    def on_login(self):
        subrequest = requests.Subscribe(path='/System/Network/Clients/Users/Login/',on_add=self.handle_login)
        self.send_request(subrequest)
        
    def handle_login(self,env,path,credentials):
        raise NotImplementedError('handle_login must be handled by a sub-class')
        
    def post_authorized(self,credentials):
        path = ''.join(('/System/Network/Clients/Connecting/',str(credentials.name),'/'))
        iobject = ioelement.IOElement('Response',{'type':'[Authorized]','username':credentials.username,'group':credentials.group})
        request = requests.Add(path=path,iobject=iobject)
        self.send_request(request)
        
    def post_unauthorized(self,credentials):
        path = ''.join(('/System/Network/Clients/Connecting/',str(credentials.name),'/'))
        iobject = ioelement.IOElement('Response',{'type':'[Unauthorized]'})
        request = requests.Add(path=path,iobject=iobject)
        self.send_request(request)
    
        
    
        